package com.example.onlinemarket.activity;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.onlinemarket.R;
import com.example.onlinemarket.adapter.RecyclerViewAdapter;
import com.example.onlinemarket.model.Good;
import com.example.onlinemarket.model.User;
import com.example.onlinemarket.util.ActivityUtil;
import com.example.onlinemarket.util.JSONUtil;
import com.google.gson.reflect.TypeToken;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.hdodenhof.circleimageview.CircleImageView;

import static com.example.onlinemarket.Application.dismissProgressDialog;
import static com.example.onlinemarket.Application.loginUser;
import static com.example.onlinemarket.Application.showProgressDialog;
import static com.example.onlinemarket.util.ActivityUtil.showBigImage;
import static com.example.onlinemarket.util.HttpUtil.sendHttpRequest;

public class ShopActivity extends BaseActivity {

    private User shop;
    private List<Good> goodList;

    private CircleImageView shopImg;
    private TextView shopNameTv;
    private TextView shopEmailTv;
    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private RecyclerViewAdapter<Good> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop);
        //初始化组件
        initWidgets();
        //初始化数据
        initData();
        //关闭加载提示框
        dismissProgressDialog();
    }

    @Override
    protected void onPostResume() {
        if(goodList.size()==0)
            getShopGoods();
        super.onPostResume();
    }

    //初始化数据
    private void initData() {
        goodList = new ArrayList<>();
        this.shop = getIntent().getParcelableExtra("shop");
        Glide.with(this).load(shop.getLocalPath()).override(350,350).placeholder(R.drawable.ic_no_img)
                .skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.NONE).into(shopImg);
        shopImg.setOnClickListener(v -> showBigImage(shop.getLocalPath()));
        shopNameTv.setText(shop.getUserName());
        shopEmailTv.setText(shop.getEmail());
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(getAdapter());
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableLoadMoreWhenContentNotFull(true);
    }

    //初始化组件
    private void initWidgets() {
        shopImg = findViewById(R.id.iv_shop_info_img);
        shopNameTv = findViewById(R.id.tv_shop_name);
        shopEmailTv = findViewById(R.id.tv_shop_email);
        refreshLayout = findViewById(R.id.layout_refresh);
        recyclerView = findViewById(R.id.recycler_view);
    }

    private void getShopGoods(){
        new Thread(() -> {
            runOnUiThread(() -> showProgressDialog(ShopActivity.this));
            Map<String, String> map = new HashMap<>();
            map.put("userId", String.valueOf(shop.getUserId()));
            String responseData = sendHttpRequest("/enterShop", "POST",map);
            if(responseData!=null&&!responseData.isEmpty()){
                goodList = JSONUtil.fromJsons(responseData, new TypeToken<List<Good>>() {}.getType());
                for(Good good : goodList){
                    good.getGoodImg();//获取所有商品对应的照片
                }
            }
            runOnUiThread(() -> {
                recyclerView.setAdapter(getAdapter());
                dismissProgressDialog();
            });
        }).start();
    }

    //获取RecyclerView对应的Adapter
    private RecyclerViewAdapter<Good> getAdapter(){
        return new RecyclerViewAdapter<Good>(this, R.layout.good_item, goodList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.good_item;
            }

            @Override
            public void convert(ViewHolder holder, Good data, int position) {
                //显示商品图片
                holder.setImage(R.id.good_img, data.getImgPath());
                holder.setOnClickListener(R.id.good_img, v -> showBigImage(data.getLocalPath()));
                //显示商品名称
                holder.setText(R.id.good_name, data.getGoodName());
                //显示商品价格
                holder.setText(R.id.good_price, String.valueOf(data.getSellPrice()));
                //点击按钮将商品添加到购物车
                holder.setOnClickListener(R.id.btn_good_item_add_shopping_cart, v -> new Thread(() -> {
                    int goodId = goodList.get(position).getGoodId();
                    Map<String, String> map = new HashMap<>();
                    map.put("goodId", String.valueOf(goodId));
                    map.put("userId", String.valueOf(loginUser.getUserId()));
                    sendHttpRequest("/addGood", "POST", map);
                    runOnUiThread(() -> Toast.makeText(context, "添加到购物车成功", Toast.LENGTH_SHORT).show());
                }).start());
            }
        };
    }
}